<?php

namespace App\Http\Controllers\Admin;

use App\Dao\MenuDao;
use App\Models\AdminGroup;
use Illuminate\Support\Facades\Auth;

class HomeController extends BaseAdminController
{

	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * 后台首页
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function index()
	{
		// 取得当前用户组
		$user = Auth::user();
		$admin_group = AdminGroup::select([
			'privs',
			'groupid',
			'groupname'
		])->findOrFail($user->groupid);
		$user->groupname = $admin_group->groupname;
		$group_privs = $admin_group->privs;

		// 初始化默认页
		$default_home_page = '';
		if (is_array(json_decode($group_privs, true))) {
			$menu = MenuDao::get_admin_menu();
			// 取出带链接的菜单
			$menu_list = [];
			foreach ($menu as $m) {
				if (isset($m['priv']) && isset($m['url']) && $m['priv'] && $m['url']) {
					$menu_list[md5($m['priv'])] = $m['url'];
				}
				if (isset($m['nodes']) && is_array($m['nodes'])) {
					foreach ($m['nodes'] as $n) {
						if (isset($n['priv']) && isset($n['url']) && $n['priv'] && $n['url']) {
							$menu_list[md5($n['priv'])] = $n['url'];
						}
					}
				}
			}
			// 默认显示第一个页面
			$group_privs_array = json_decode($group_privs, true);
			foreach ($group_privs_array as $p) {
				if (isset($menu_list[md5($p)])) {
					$default_home_page = $menu_list[md5($p)];
					break;
				}
			}
		}

		if ($default_home_page == '') {
			$default_home_page = route('admin.user.users');
		}

		return view('admin.home', [
			'user' => $user,
			'default_home_page' => $default_home_page
		]);
	}

	public function welcome()
	{
	}
}
